package com.lin.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.blog.entity.RolePermission;
import com.lin.blog.mapper.RolePermissionMapper;
import com.lin.blog.service.IRolePermissionService;
import com.lin.constant.ResultCode;
import com.lin.utils.ListUtils;
import com.lin.utils.Result;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lin
 * @since 2020-03-08
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 通过roleId更新权限
     * @param roleId
     * @param permissionList
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateRolePermission(Long roleId, List<Long> permissionList){
        if (roleId == null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK);
        }

        // 从数据库中通过 roleId 获取 rolePermissionsList
        List<RolePermission> rolePermissions = rolePermissionMapper.listRolePermissionByRoleId(roleId);

        List<Long> permissionListFromDB = new ArrayList<>();
        for (RolePermission rolePermission: rolePermissions){
            permissionListFromDB.add(rolePermission.getPermissionId());
        }

        // 删除列表 则 前端传输的permissionList 不存在  数据库的 permissionListFromDB存在
        List<Long> deletePermissionList  =  ListUtils.getDifference(permissionListFromDB,permissionList);

        // 增加列表 则 前端传输的permissionList 存在,  数据库的 permissionListFromDB不存在
        List<Long> insertPermissionList  =  ListUtils.getDifference(permissionList,permissionListFromDB);



        // 批量删除添加
        if (deletePermissionList.size()!=0){
            rolePermissionMapper.deleteBatch(roleId,deletePermissionList);
        }

        // 批量添加元素
        if (insertPermissionList.size()!=0){
            rolePermissionMapper.insertBatch(roleId,insertPermissionList);
        }

        return Result.success();
    }
}
